<template>
  <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8 sm:py-12">
    <div class="mb-6">
      <UButton
        to="/blog"
        variant="ghost"
        color="neutral"
        icon="i-lucide-arrow-left"
        label="Back to Blog"
        size="sm"
      />
    </div>

    <XMarkBlogDetail
      v-if="displayPost"
      :post="displayPost"
      :previous-post="surround?.previous ?? undefined"
      :next-post="surround?.next ?? undefined"
      :toc="tocLinks"
    >
      <ContentRenderer
        v-if="rawPost"
        :value="rawPost"
      />
    </XMarkBlogDetail>
  </div>
</template>

<script setup lang="ts">
const route = useRoute()
const { getSurround, normalizeBlogPost } = useXBlog()

// Opt-out: xMarketing.blog.active === false disables the shipped blog pages.
if (useAppConfig()?.xMarketing?.blog?.active === false) {
  throw createError({ statusCode: 404, statusMessage: 'Page not found' })
}

const path = computed(() => {
  const slug = route.params.slug
  const parts = Array.isArray(slug) ? slug : [slug]
  return `/blog/${parts.filter(Boolean).join('/')}`
})

const { data: rawPost } = await useAsyncData(
  () => `marketing-blog-post-${path.value}`,
  () => queryCollection('blog').path(path.value).first(),
)

if (!rawPost.value) {
  throw createError({
    statusCode: 404,
    statusMessage: 'Post not found',
  })
}

const displayPost = computed(() =>
  rawPost.value ? normalizeBlogPost(rawPost.value as unknown as Record<string, unknown>) : null,
)

const { data: surround } = await useAsyncData(
  () => `marketing-blog-surround-${path.value}`,
  () => getSurround(path.value),
)

type TocLink = { id: string; text: string; depth: number }

const tocLinks = computed((): TocLink[] => {
  const body = (rawPost.value as { body?: { toc?: { links?: TocLink[] } } } | null)?.body
  return body?.toc?.links ?? []
})

const title = computed(() => displayPost.value?.title)
const description = computed(() =>
  typeof displayPost.value?.description === 'string'
    ? displayPost.value.description
    : undefined,
)
const ogImage = computed(() => displayPost.value?.img?.src ?? displayPost.value?.image)

useSeoMeta({
  title,
  ogTitle: title,
  description,
  ogDescription: description,
  ogImage,
})
</script>
